import React, { useState, useEffect, useRef } from 'react'
import { useHistory, useParams } from 'react-router-dom'
import styled from 'styled-components'
import DocumentTitle from 'react-document-title'
import { _isDev } from '@api/config'

import { getWxAcode, getShareData } from '@api'
import axios from 'axios'

const ShareCanvas = (props) => {

    const history = useHistory()
    const [shareGroupData, setShareGroupData] = useState({})
    const params = useParams()

    const shareImg = useRef()
    const tempImg = useRef()
    const acode = useRef()
    const myCanvas = useRef()

    const hash = `pages/home-login/main?url=groupid/${params.tuanid}`
    const config = {
        appid: _isDev ? 'wxeaef65640a28d704' : 'wxb02d1cee9d232633',
        secret: _isDev ? '2ce25911a67c1c92c9940943ac676af6' : 'bf23d6385636525e5b08f38afd8070d7',
        action: 'getWxAcode',
        path: hash,
        type: 1
    }
    const config2 = {
        action: 'shareGroupImg',
        tuan_id: params.tuanid
    }
    const system = detect()


    useEffect(() => {
        // 小程序【火蝶NBE】
        // AppID(小程序ID): wxeaef65640a28d704
        // AppSecret(小程序密钥): 2ce25911a67c1c92c9940943ac676af6

        // 火蝶云BOSS
        // AppID(小程序ID) ：wxb02d1cee9d232633
        // AppSecret(小程序密钥): bf23d6385636525e5b08f38afd8070d7
        axios.all([getWxAcode(config), getShareData(config2)]).then(axios.spread((res1, res2) => {
            setShareGroupData(Object.assign({}, { acode: res1, groupData: res2.data, img: `https://res.lexiangpingou.cn/${res2.data.goodsimg}` }))
        }))

    }, [params])


    useEffect(() => {
        const drawing = myCanvas.current
        // const url = 'https://img.pddpic.com/mms-material-img/2020-10-29/838066fd-e71a-4f55-8aab-b6e4b8728738.jpeg.a.jpeg'
        getBase64Img(shareGroupData.img, tempImg.current)

        if (drawing.getContext && shareGroupData.groupData) {
            
            const { endtime, goodsname, lacknum, neednum, oprice, sprice, unit } = shareGroupData.groupData

            let time = timer(endtime)
            let yp = parseInt(neednum) - parseInt(lacknum)
            let bfb = yp / parseInt(neednum)
            let context = setupCanvas(drawing)

            // 上部分画布
            context.fillStyle = 'rgba(255,255,255, .3)'
            context.fillRect(0, 0, Rpx(568), Rpx(450))
            context.fillStyle = "white"
            context.font = `bold ${Rpx(30)}px  PingFang SC`
            context.fillText('图片丢失', Rpx(225), Rpx(244),)
            context.fillText('请重新生成', Rpx(210), Rpx(284))

            // 绘制image
            try {
                context.drawImage(tempImg.current, 0, 0, Rpx(568), Rpx(450))
            } catch (e) {
                console.log(e)
            }

            // 下半部分画布
            context.fillStyle = "white"
            context.fillRect(0, Rpx(450), Rpx(568), Rpx(439))

            // 商品标题
            context.fillStyle = "#474747"
            context.font = `bold ${Rpx(24)}px  PingFang SC`
            context.textAlign = "start"
            context.textBaseline = 'top'
            context.textBaseline = "middle"
            textPrewrap(context, goodsname, Rpx(90), Rpx(492), 36, Rpx(436), 2)

            // 商品类型 
            context.fillStyle = '#CF292B'
            context.fillRect(Rpx(30), Rpx(478), Rpx(52), Rpx(26))

            context.font = `bold ${Rpx(18)}px  PingFang SC`
            context.fillStyle = "white"
            context.fillText('拼货', Rpx(38), Rpx(492))

            //已拼多少
            context.fillStyle = '#474747'
            context.font = `bold ${Rpx(22)}px  PingFang SC`
            context.textAlign = "center"
            let yp_y = Rpx(602)
            let yp_width = context.measureText(`已拼${yp}件还剩`).width
            let lacknum_width = context.measureText(lacknum).width
            let jian_width = context.measureText('件').width
            let form_the_left = (568 - ((yp_width + lacknum_width + jian_width) / 2)) / 2


            context.fillText(`已拼${yp}件还剩`, Rpx(form_the_left), yp_y)
            context.fillStyle = "#ff762e"
            context.fillText(lacknum, Rpx((yp_width + form_the_left)), yp_y)
            context.fillStyle = "#474747"
            context.fillText('件', Rpx((yp_width + lacknum_width + form_the_left + 10)), yp_y)

            let schedule
            if ((bfb * 538) < 20) {
                schedule = 30
            } else {
                schedule = bfb * 538
            }

            // 进度条
            const schedule_y = Rpx(632)
            context.fillStyle = '#c7c7c7'
            context.beginPath()
            context.arc(30, schedule_y, 7, Math.PI * 0.5, Math.PI * 1.5, false)
            context.arc(538, schedule_y, 7, Math.PI * 1.5, Math.PI * 0.5, false)
            context.fill()

            context.beginPath()
            context.fillStyle = '#ff762e'
            context.arc(30, schedule_y, 7, Math.PI * 0.5, Math.PI * 1.5, false)
            context.arc(schedule, schedule_y, 7, Math.PI * 1.5, Math.PI * 0.5, false)
            context.fill()

            // 拼单时间剩余
            context.fillStyle = "#474747"
            context.font = `bold ${Rpx(18)}px  PingFang SC`
            context.fillText(`拼单剩余时间`, Rpx(284), Rpx(664))

            // 倒计时
            const cube = Rpx(686)
            context.fillStyle = '#FF4B4B'
            context.fillRect(Rpx(118), cube, Rpx(30), Rpx(30))
            context.fillRect(Rpx(208), cube, Rpx(30), Rpx(30))
            context.fillRect(Rpx(298), cube, Rpx(30), Rpx(30))
            context.fillRect(Rpx(388), cube, Rpx(30), Rpx(30))

            // time
            const time_y = Rpx(700)
            context.fillStyle = 'white'
            context.font = `bold ${Rpx(22)}px  PingFang SC`
            context.textAlign = "center"
            context.textBaseline = 'center'
            context.fillText(time.day, Rpx(133), time_y, Rpx(30))
            context.fillText(time.hour, Rpx(223), time_y, Rpx(30))
            context.fillText(time.min, Rpx(313), time_y, Rpx(30))
            context.fillText(time.sec, Rpx(403), time_y, Rpx(30))

            const time_text_y = Rpx(702)
            // 天 时 分 秒
            context.fillStyle = "#474747"
            context.fillText("天", Rpx(166), time_text_y)
            context.fillText("时", Rpx(256), time_text_y)
            context.fillText("分", Rpx(346), time_text_y)
            context.fillText("秒", Rpx(440), time_text_y)


            // 左下角 price 售价
            context.fillStyle = '#C1C1C1'
            context.font = `500 ${Rpx(18)}px PingFang-SC-Medium`
            context.textAlign = "start"
            context.textBaseline = 'top'
            context.fillText(`售价：￥${sprice ? sprice : ''}`, Rpx(30), Rpx(776))

            // 划线
            // 创建路径
            context.strokeStyle = "#c1c1c1"
            context.beginPath()
            context.moveTo(Rpx(28), system === 'ios' ? Rpx(788) : Rpx(782))
            context.lineTo(Rpx(140), system === 'ios' ? Rpx(788) : Rpx(782))
            context.stroke()

            // ￥
            context.fillStyle = '#ff762e'
            context.font = `500 ${Rpx(18)}px PingFang-SC-Medium`
            context.fillText('￥', Rpx(30), Rpx(808))

            // 8.00/件
            context.font = `bold ${Rpx(26)}px PingFang SC`
            context.fillText(`${oprice}/${unit}`, Rpx(48), Rpx(800))


            //  二维码旁白
            context.fillStyle = '#c1c1c1'
            context.font = `500 ${Rpx(18)}px PingFang-SC-Medium`
            context.textAlign = "start"
            context.fillText('一群人正在参与拼单', Rpx(247), Rpx(760))
            context.fillText('长按识别二维码', Rpx(283), Rpx(794))
            context.fillText('参与拼单', Rpx(338), Rpx(828))

            context.drawImage(acode.current, Rpx(423), Rpx(746), Rpx(115), Rpx(115))
            shareImg.current.src = drawing.toDataURL()
            myCanvas.current.style = 'display: none'
        }

        // tempImg.current.onload = huahua(drawing, system)
    }, [shareGroupData])

    return (
        <>
            <DocumentTitle title={props.route.title} />
            <ShareCanvasStyle>
                <div className="goback"
                    onClick={e => {
                        history.goBack()
                    }}
                >
                    返回
                </div>

                <canvas ref={myCanvas}>  该环境不支持canvas </canvas>

                <img src="" alt="" ref={tempImg} className="tempimg" />

                <img className="shareimg" src="" alt="" ref={shareImg} />

                {shareGroupData.acode && <img src={shareGroupData.acode} ref={acode} alt="" className="acode" crossOrigin="anonymous" />}

            </ShareCanvasStyle>
        </>

    )

    function huahua(drawing, system) {
        if (drawing.getContext && shareGroupData.groupData) {

            const { endtime, goodsname, lacknum, neednum, oprice, sprice, unit } = shareGroupData.groupData


            let time = timer(endtime)
            let yp = parseInt(neednum) - parseInt(lacknum)
            let bfb = yp / parseInt(neednum)
            let context = setupCanvas(drawing)

            // 上部分画布
            context.fillStyle = 'rgba(255,255,255, .3)'
            context.fillRect(0, 0, Rpx(568), Rpx(450))
            context.fillStyle = "white"
            context.font = `bold ${Rpx(30)}px  PingFang SC`
            context.fillText('图片丢失', Rpx(225), Rpx(244),)
            context.fillText('请重新生成', Rpx(210), Rpx(284))


            // 绘制image
            try {
                context.drawImage(tempImg.current, 0, 0, Rpx(568), Rpx(450))
            } catch (e) {
                console.log(e)
            }

            // 下半部分画布
            context.fillStyle = "white"
            context.fillRect(0, Rpx(450), Rpx(568), Rpx(439))

            // 商品标题
            context.fillStyle = "#474747"
            context.font = `bold ${Rpx(24)}px  PingFang SC`
            context.textAlign = "start"
            context.textBaseline = 'top'
            context.textBaseline = "middle"
            textPrewrap(context, goodsname, Rpx(90), Rpx(492), 36, Rpx(436), 2)

            // 商品类型 
            context.fillStyle = '#CF292B'
            context.fillRect(Rpx(30), Rpx(478), Rpx(52), Rpx(26))

            context.font = `bold ${Rpx(18)}px  PingFang SC`
            context.fillStyle = "white"
            context.fillText('拼货', Rpx(38), Rpx(492))

            //已拼多少
            context.fillStyle = '#474747'
            context.font = `bold ${Rpx(22)}px  PingFang SC`
            context.textAlign = "center"
            let yp_y = Rpx(602)
            let yp_width = context.measureText(`已拼${yp}件还剩`).width
            let lacknum_width = context.measureText(lacknum).width
            let jian_width = context.measureText('件').width
            let form_the_left = (568 - ((yp_width + lacknum_width + jian_width) / 2)) / 2


            context.fillText(`已拼${yp}件还剩`, Rpx(form_the_left), yp_y)
            context.fillStyle = "#ff762e"
            context.fillText(lacknum, Rpx((yp_width + form_the_left)), yp_y)
            context.fillStyle = "#474747"
            context.fillText('件', Rpx((yp_width + lacknum_width + form_the_left + 10)), yp_y)

            let schedule
            if ((bfb * 538) < 20) {
                schedule = 30
            } else {
                schedule = bfb * 538
            }

            // 进度条
            const schedule_y = Rpx(632)
            context.fillStyle = '#c7c7c7'
            context.beginPath()
            context.arc(30, schedule_y, 7, Math.PI * 0.5, Math.PI * 1.5, false)
            context.arc(538, schedule_y, 7, Math.PI * 1.5, Math.PI * 0.5, false)
            context.fill()

            context.beginPath()
            context.fillStyle = '#ff762e'
            context.arc(30, schedule_y, 7, Math.PI * 0.5, Math.PI * 1.5, false)
            context.arc(schedule, schedule_y, 7, Math.PI * 1.5, Math.PI * 0.5, false)
            context.fill()

            // 拼单时间剩余
            context.fillStyle = "#474747"
            context.font = `bold ${Rpx(18)}px  PingFang SC`
            context.fillText(`拼单剩余时间`, Rpx(284), Rpx(664))

            // 倒计时
            const cube = Rpx(686)
            context.fillStyle = '#FF4B4B'
            context.fillRect(Rpx(118), cube, Rpx(30), Rpx(30))
            context.fillRect(Rpx(208), cube, Rpx(30), Rpx(30))
            context.fillRect(Rpx(298), cube, Rpx(30), Rpx(30))
            context.fillRect(Rpx(388), cube, Rpx(30), Rpx(30))

            // time
            const time_y = Rpx(700)
            context.fillStyle = 'white'
            context.font = `bold ${Rpx(22)}px  PingFang SC`
            context.textAlign = "center"
            context.textBaseline = 'center'
            context.fillText(time.day, Rpx(133), time_y, Rpx(30))
            context.fillText(time.hour, Rpx(223), time_y, Rpx(30))
            context.fillText(time.min, Rpx(313), time_y, Rpx(30))
            context.fillText(time.sec, Rpx(403), time_y, Rpx(30))

            const time_text_y = Rpx(702)
            // 天 时 分 秒
            context.fillStyle = "#474747"
            context.fillText("天", Rpx(166), time_text_y)
            context.fillText("时", Rpx(256), time_text_y)
            context.fillText("分", Rpx(346), time_text_y)
            context.fillText("秒", Rpx(440), time_text_y)


            // 左下角 price 售价
            context.fillStyle = '#C1C1C1'
            context.font = `500 ${Rpx(18)}px PingFang-SC-Medium`
            context.textAlign = "start"
            context.textBaseline = 'top'
            context.fillText(`售价：￥${sprice ? sprice : ''}`, Rpx(30), Rpx(776))

            // 划线
            // 创建路径
            context.strokeStyle = "#c1c1c1"
            context.beginPath()
            context.moveTo(Rpx(28), system === 'ios' ? Rpx(788) : Rpx(782))
            context.lineTo(Rpx(140), system === 'ios' ? Rpx(788) : Rpx(782))
            context.stroke()

            // ￥
            context.fillStyle = '#ff762e'
            context.font = `500 ${Rpx(18)}px PingFang-SC-Medium`
            context.fillText('￥', Rpx(30), Rpx(808))

            // 8.00/件
            context.font = `bold ${Rpx(26)}px PingFang SC`
            context.fillText(`${oprice}/${unit}`, Rpx(48), Rpx(800))


            //  二维码旁白
            context.fillStyle = '#c1c1c1'
            context.font = `500 ${Rpx(18)}px PingFang-SC-Medium`
            context.textAlign = "start"
            context.fillText('一群人正在参与拼单', Rpx(247), Rpx(760))
            context.fillText('长按识别二维码', Rpx(283), Rpx(794))
            context.fillText('参与拼单', Rpx(338), Rpx(828))

            context.drawImage(acode.current, Rpx(423), Rpx(746), Rpx(115), Rpx(115))
            shareImg.current.src = drawing.toDataURL()
            myCanvas.current.style = 'display: none'
        }
    }

    function getBase64Img(url, ref) {
        let image = new Image()
        image.src = url + '?v=' + Math.random()  //处理缓存
        image.crossOrigin = "*"
        image.onload = function () {
            let base64 = drawBase64Image(image)
            ref.src = base64
        }

    }


    /**
     * 
     * @param {*} ctx 画布的上下文环境
     * @param {*} content 需要绘制的文本内容
     * @param {*} drawX 绘制文本的x坐标
     * @param {*} drawY 绘制文本的y坐标
     * @param {*} lineHeight 文本之间的行高
     * @param {*} lineMaxWidth 每行文本的最大宽度
     * @param {*} lineNum 最多绘制的行数
     */
    function textPrewrap(ctx, content, drawX, drawY, lineHeight, lineMaxWidth, lineNum) {
        var drawTxt = ''; // 当前绘制的内容
        var drawLine = 1; // 第几行开始绘制
        var drawIndex = 0; // 当前绘制内容的索引

        // 判断内容是否可以一行绘制完毕
        if (ctx.measureText(content).width <= lineMaxWidth) {
            ctx.fillText(content.substring(drawIndex, i), drawX, drawY);
        } else {
            for (var i = 0; i < content.length; i++) {
                drawTxt += content[i];
                if (ctx.measureText(drawTxt).width >= lineMaxWidth) {
                    if (drawLine >= lineNum) {
                        ctx.fillText(content.substring(drawIndex, i) + '...', drawX - 60, drawY);
                        break;
                    } else {
                        ctx.fillText(content.substring(drawIndex, i + 1), drawX, drawY);
                        drawIndex = i + 1;
                        drawLine += 1;
                        drawY += lineHeight;
                        drawTxt = '';
                    }
                } else {
                    // 内容绘制完毕，但是剩下的内容宽度不到lineMaxWidth
                    if (i === content.length - 1) {
                        ctx.fillText(content.substring(drawIndex), drawX, drawY);
                    }
                }
            }
        }
    }

    function drawBase64Image(img) {
        let canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        let ctx = canvas.getContext('2d')
        ctx.drawImage(img, 0, 0, img.width, img.height)
        let dataURL = canvas.toDataURL('image/png')
        return dataURL
    }

    /**
     * @description:判断手机系统
     * @param {*}
     * @return {*}
     */
    function detect() {
        let u = navigator.userAgent
        let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
        let isIos = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
        if (isAndroid) {
            return 'android'
        }
        if (isIos) {
            return 'ios'
        }

        return false
    }

    /**
     * @description:创建一个两倍于实际大小的 canvas ， 然后用css 样式把canvas 限定在实际的大小。
     * @param {*} canvas
     * @return {*} canvas context
     */
    function setupCanvas(canvas) {
        // Get the device pixel ratio, falling back to 1.
        var dpr = window.devicePixelRatio || 1;
        // Get the size of the canvas in CSS pixels.
        var rect = canvas.getBoundingClientRect();
        // Give the canvas pixel dimensions of their CSS
        // size * the device pixel ratio.
        canvas.width = rect.width * dpr;
        canvas.height = rect.height * dpr;
        var ctx = canvas.getContext('2d');
        // Scale all drawing operations by the dpr, so you
        // don't have to worry about the difference.
        ctx.scale(dpr, dpr);
        return ctx;
    }

    /**
     * @description: 
     * @param {*number} n
     * @return {*}
     */
    function Rpx(n) {
        return n
    }

    function timer(expiredTime) {

        let timerObj = {}
        let now = parseInt(expiredTime) - Date.parse(new Date()) / 1000

        if (now < 0) {
            return { day: '00', hour: '00', min: '00', sec: '00' }
        } else {
            timerObj.day = Math.floor(now / 3600 / 24);
            timerObj.hour = Math.floor((now - timerObj.day * 3600 * 24) / 3600);
            timerObj.min = Math.floor((now - timerObj.day * 3600 * 24 - timerObj.hour * 3600) / 60);
            timerObj.sec = now - timerObj.day * 3600 * 24 - timerObj.hour * 3600 - timerObj.min * 60;

            if (timerObj.day.toString().length === 1) {
                timerObj.day = '0' + timerObj.day
            } else if (timerObj.day === 0) {
                timerObj.day = '00'
            }

            if (timerObj.hour.toString().length === 1) {
                timerObj.hour = '0' + timerObj.hour
            }
            if (timerObj.min.toString().length === 1) {
                timerObj.min = '0' + timerObj.min
            }
            if (timerObj.hour.toString().length === 1) {
                timerObj.sec = '0' + timerObj.sec
            }
            return timerObj
        }
    }
}

export default ShareCanvas

const ShareCanvasStyle = styled.div`

    text-align: center;
    box-sizing: border-box;
    padding: 2.09rem 1.21rem;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0,0,0, .3);

    .goback{
        width: .8rem;
        height: .8rem;
        border-radius: 50%;
        background-color: white;
        border: solid 1px white;
        position: fixed;
        line-height: .8rem;
        left: 1rem;
        top:  1rem;
    }

    .mask{
        position: absolute;
        width: 100vw;
        height: 100vh;
        background-color: rgba(0,0,0, .3)
    }

    canvas{
        width:568px;
        height: 889px;
        opacity: 0;
    }

    .acode{
        display: none;
        width: 1.77rem;
        height: 1.77rem;
    }

    .tempimg{
        width:284px;
        height: 225px;
        display:none;
    }

  
    .shareimg{
       width:284px;
       height: 444.5px;
    }




`

